<?php
namespace Home\Controller;

class UserController extends HomeController {

	function index($id='') {
		if (empty($id)) {
			
		}else {
			$map['uid'] = $id;
			$member = D('Member');
			$info   = $member->find($id);
			!$info && $this->error('您查看的会员不存在！');
			$this->assign('info', $info);
			$this->display();
		}
	}

	function register($username='', $password='', $repassword='', $email='', $mobile='') {
		if (IS_POST) {
			/* 检测密码 */
			if($password != $repassword){
				$this->error('密码和重复密码不一致！');
			}			
			/* 调用注册接口注册用户 */
			$User = new \User\Api\UserApi;
			$uid = $User->register($username, $password, $email ,$mobile);
			if(0 < $uid){ //注册成功
				//TODO: 发送验证邮件
				$this->success('注册成功！',U('/login'));
			} else { //注册失败，显示错误信息
				$this->error($this->showRegError($uid));
			}
		}else {
			if (is_login()) {
				$this->redirect('/index');
			}else {
				$this->title('用户注册');
				$this->display();
			}
		}
	}

	function login($username = '', $password = '', $verify = '') {
		if (IS_POST) {
			/* 调用UC登录接口登录 */
			$user = new \User\Api\UserApi;
			$uid = $user->login($username, $password);
			if(0 < $uid){ //UC登录成功
				/* 登录用户 */
				$Member = D('Member');
				if($Member->login($uid)){ //登录用户
					//跳转到登录前页面
					$this->success('登录成功！', get_redirect_url());
				} else {
					$this->error($Member->getError());
				}
			} else { //登录失败
				switch($uid) {
					case -1: $error = '用户不存在或被禁用！'; break; //系统级别禁用
					case -2: $error = '密码错误！'; break;
					default: $error = '未知错误！'; break; // 0-接口参数错误
				}
				$this->error($error);
			}
		}else {
			if (is_login()) {
				$this->redirect('/index');
			}else {
				$this->title('用户登陆');
				$this->display();
			}
		}
	}
	
	/* 退出登录 */
	public function logout(){
		if(is_login()){
			D('Member')->logout();
			$this->success('退出成功！', U('/index'));
		} else {
			$this->redirect('/login');
		}
	}
	
	/**
	 * 获取用户注册错误信息
	 * @param  integer $code 错误编码
	 * @return string        错误信息
	 */
	private function showRegError($code = 0){
		switch ($code) {
			case -1:  $error = '用户名长度必须在16个字符以内！'; break;
			case -2:  $error = '用户名被禁止注册！'; break;
			case -3:  $error = '用户名被占用！'; break;
			case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
			case -5:  $error = '邮箱格式不正确！'; break;
			case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
			case -7:  $error = '邮箱被禁止注册！'; break;
			case -8:  $error = '邮箱被占用！'; break;
			case -9:  $error = '手机格式不正确！'; break;
			case -10: $error = '手机被禁止注册！'; break;
			case -11: $error = '手机号被占用！'; break;
			default:  $error = '未知错误';
		}
		return $error;
	}
}